package file

import (
	"context"
	"fmt"

	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/logic/media/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFileByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetFileByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFileByIdLogic {
	return &GetFileByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetFileByIdLogic) GetFileById(req *types.UUIDReq) (resp *types.MediaFileInfoResp, err error) {
	data, err := l.svcCtx.AttachmentRpc.BackendGetFileById(l.ctx, &attachmentclient.FileIdReq{
		Id:       req.Id,
		WithMeta: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return
	}

	var meta []*types.MetaInfo
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	option := util.GetOptionByStatusAndType(data.Status, data.Type)

	var url *string
	if data.Url != nil && len(*data.Url) > 0 {
		url = pointy.GetPointer(fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *data.Url))
	}
	var uri *string
	if data.Path != nil && len(*data.Path) > 0 {
		uri = pointy.GetPointer(fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *data.Path))
	}
	if url == nil || len(*url) == 0 {
		url = uri
	}

	return &types.MediaFileInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.MediaFileInfo{
			BaseUUIDInfo: types.BaseUUIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Filename: data.Filename,
			// Name:     data.Filename,
			Path:     uri,
			Url:      url,
			FileType: data.Type,
			MimeType: data.MimeType,
			Size:     data.Size,
			Md5:      data.Md5,
			ParentId: data.ParentId,
			UserId:   data.UserId,
			AltText:  data.AltText,
			// Title:         data.AltText,
			Excerpt:       data.Excerpt,
			Status:        data.Status,
			Sort:          data.Sort,
			Password:      data.Password,
			CommentStatus: data.CommentStatus,
			CommentCount:  data.CommentCount,
			// Count:         data.Count,
			Meta:         meta,
			CanPut:       option.CanPut,
			CanWatermark: option.CanWatermark,
			CanThumbnail: option.CanThumbnail,
		},
	}, nil
}
